<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
    <head>
        <meta name="keywords" content="objective-c objectivec obj-c objc tutorial howto beginners beginner's guide intro"/>
        <meta name="description" content="Beginner's guide to Objective-C with practical coding examples that contrast Objective-C to other OOP languages like Java and C++"/>
        <title>Objective-C Beginner's Guide</title>
        <style type="text/css">
            pre.code {
                border: 1px gray solid;
                background-color: #eeeeee;
                padding: 5px;
            }
            pre.output {
                border: 1px gray solid;
                background-color: #EEE7C0;
                padding: 5px;
            }
        </style>
    </head>
    <body>
        <div style="text-align: right;">Translations: English | <a href="objective-c.html.zh-tw.big5">Chinese</a></div>
        <h1>Outline</h1>
        <ul>
            <li><a href="#gettingstarted">Getting Started</a></li>
            <ul>
                <li><a href="#downloading">Downloading this tutorial</a></li>
                <li><a href="#settingup">Setting up the environment</a></li>
                <li><a href="#preamble">Preamble</a></li>
                <li><a href="#helloworld">Making hello world</a></li>
            </ul>
            <li><a href="#creatingclasses">Creating Classes</a></li>
            <ul>
                <li><a href="#interface">@interface</a></li>
                <li><a href="#implementation">@implementation</a></li>
                <li><a href="#piecing">Piecing it together</a></li>
            </ul>
            <li><a href="#thedetails">The Details...</a></li>
            <ul>
                <li><a href="#multiple">Multiple Parameters</a></li>
                <li><a href="#constructors">Constructors</a></li>
                <li><a href="#access">Access Privledges</a></li>
                <li><a href="#class">Class level access</a></li>
                <li><a href="#exceptions">Exceptions</a></li>
            </ul>
            <li><a href="#inheritance">Inheritance, Polymorphism, and other OOP features</a></li>
            <ul>
                <li><a href="#idtype">The id type</a></li>
                <li><a href="#subinheritance">Inheritance</a></li>
                <li><a href="#dynamictypes">Dynamic types</a></li>
                <li><a href="#categories">Categories</a></li>
                <li><a href="#posing">Posing</a></li>
                <li><a href="#protocols">Protocols</a></li>
            </ul>
            <li><a href="#memorymanagement">Memory Management</a></li>
            <ul>
                <li><a href="#retain">Retain and Release</a></li>
                <li><a href="#dealloc">Dealloc</a></li>
                <li><a href="#autorelease">Autorelease Pool</a></li>
            </ul>
            <li><a href="#foundation">Foundation Framework Classes</a></li>
            <ul>
                <li><a href="#nsarray">NSArray</a></li>
                <li><a href="#nsdictionary">NSDictionary</a></li>
            </ul>
            <li><a href="#prosandcons">Pros and Cons</a></li>
            <li><a href="#moreinfo">More Information</a></li>
        </ul>
        <hr />
        <ul>
            <li><h1>Getting Started</h1><a name="gettingstarted"></a></li>
            <ul>
                <li><h2>Downloading this tutorial</h2><a name="downloading"></a></li>
                <ul>
                    <li>All the source code for this beginners guide including makefiles is available by downloading <a href="files/objc.tar.gz">objc.tar.gz</a>.  Many of the examples in this tutorial were written by Steve Kochan in the book "Programming in Objective-C."  If you want more detailed information and examples, feel free to check out his book.  The examples on this site were used with his permission, so please don't copy them.</li>
                </ul>
                <li><h2>Setting up the environment</h2><a name="settingup"></a></li>
                <ul>
                    <li>Linux/FreeBSD: Install <a href="http://www.gnustep.org">GNUStep</a></li>
                    <ul>
                        <li>In order to build GNUstep applications one must first execute the GNUstep.sh file in /usr/GNUstep/System/Makefiles/GNUstep.sh.  This path depends on your system. Some put it in /usr, some /usr/lib, some /usr/local.  If your shell is a csh/tcsh based shell, you'll want to execute GNUStep.csh instead.  It's recommended that you put this script in your .bashrc or .cshrc.</li>
                    </ul>
                    <li>Mac OS X: Install <a href="http://connect.apple.com">XCode</a></li>
                    <li>Windows NT 5.X: Install <a href="http://www.cygwin.com">cygwin</a> or <a href="http://www.mingw.org">mingw</a> and then install <a href="http://www.gnustep.org">GNUStep</a></li>
                </ul>
                <li><h2>Preamble</h2><a name="preamble"></a></li>
                <ul>
                    <li>This tutorial assumes you have some basic C knowledge, including C data types, what a function is, what a return value is, knowledge of pointers and basic memory management in C.  If you haven't gotten this far, I highly suggest you pick up K and R's book, The C Programming Language, Volume 2.  This is <b>the</b> book on C written by the writers of C.</li>
                    <li>Objective-C, being a C derivative, inherits all of C's features.  There are a few exceptions but they don't really deviate from what C offers as a language.</li>
                    <li>nil: In C/C++ you're probably used to NULL.  In Objective-C it is nil.  The difference is you can pass messages to nil (such as [nil message];) and this is perfectly legal.  You cannot however do this with NULL.</li>
                    <li>BOOL: C doesn't have an official boolean type, and in reality neither does Objective-C.  It's however built into the Foundation classes (Namely from importing NSObject.h).  nil is also included in this header file.  BOOL in Objective-C has two modes, YES and NO rather than TRUE and FALSE.</li>
                    <li>#import vs #include: As you will notice in the hello world example, #import was used.  #import is supported by the gcc compiler, however it is deprecated in favor of #include.  #import is basically the same thing as #ifndef #define #endif at the top and bottom of every .h file you make.  I find this to be retarded, as many other programmers will most likely agree.  For all purposes, just use #import.  It's less hassle, and if gcc ever does remove it chances are enough Objective-C developers exist to either keep it from getting removed or getting added back in. As an aside, Apple officially uses #import in all their code so if this ever did happen, you can be certain that Apple would conviently ship a forked version of gcc to add this back in.</li>
                    <li>The word method and message are used interchangably in Objective-C, although messages have special properties.  A message can be dynamically forwarded to another object.  Calling a message on an object in Objective-C doesn't mean that the object implements that message, just that it knows how to respond to it somehow via directly implementing it or forwarding the message to an object that does know how to.</li>
                </ul>
                <li><h2>Making hello world</h2><a name="helloworld"></a></li>
                <ul>
                    <li>hello.m<pre class="code">#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    printf( "hello world\n" );
    return 0;
}</pre></li>
                    <li>output<pre class="output">hello world</pre></li>
                    <li>You use #import instead of #include in Objective-C</li>
                    <li>The default file extention for Objective-C is .m</li>
                </ul>
            </ul>
            <li><h1>Creating classes</h1><a name="creatingclasses"></a></li>
            <ul>
                <li><h2>@interface</h2><a name="interface"></a></li>
                <ul>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>Fraction.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;

@interface Fraction: NSObject {
    int numerator;
    int denominator;
}

-(void) print;
-(void) setNumerator: (int) d;
-(void) setDenominator: (int) d;
-(int) numerator;
-(int) denominator;
@end
</pre></li>
                    <li>NSObject: Short for NeXTStep Object.  Although this is less meaningful today since it's really OpenStep.</li>
                    <li>Inheritance is specified as Class: Parent, as seen with Fraction: NSObject.</li>
                    <li>Instance variables go between @interface Class: Parent { .... }</li>
                    <li>No access is set (protected, public, private).  Default is protected.  Setting the access will be shown later</li>
                    <li>Instance methods follow after the member variables. The format is: scope (returnType) methodName: (parameter1Type) parameter1Name;</li>
                    <ul>
                        <li>scope refers to class or instance. instance methods begin with <b>-</b> class level methods begin with <b>+</b></li>
                    </ul>
                    <li>Interface ends with @end</li>
                </ul>
                <li><h2>@implementation</h2><a name="implementation"></a></li>
                <ul>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>Fraction.m<pre class="code">#import "Fraction.h"
#import &lt;stdio.h&gt;

@implementation Fraction
-(void) print {
    printf( "%i/%i", numerator, denominator );
}

-(void) setNumerator: (int) n {
    numerator = n;
}

-(void) setDenominator: (int) d {
    denominator = d;
}

-(int) denominator {
    return denominator;
}

-(int) numerator {
    return numerator;
}
@end</pre></li>
                    <li>@implementation ClassName starts the implementation @end ends it</li>
                    <li>All the defined methods are implemented very simlar to how they are declared in the interface</li>
                </ul>
                <li><h2>Piecing it together</h2><a name="piecing"></a></li>
                <ul>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>main.m<pre class="code">#import &lt;stdio.h&gt;
#import "Fraction.h"

int main( int argc, const char *argv[] ) {
    // create a new instance
    Fraction *frac = [[Fraction alloc] init];

    // set the values
    [frac setNumerator: 1];
    [frac setDenominator: 3];

    // print it
    printf( "The fraction is: " );
    [frac print];
    printf( "\n" );

    // free memory
    [frac release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">The fraction is: 1/3</pre></li>
                    <li>Fraction *frac = [[Fraction alloc] init];</li>
                    <ul>
                        <li>There are several important things in this one line.</li>
                        <li>The way methods in Objective-C are called is [object method], which is similar to object-&gt;method() in C++</li>
                        <li>Objective-C doesn't have value types, so there is nothing similar to C++'s: Fraction frac; frac.print();.  You always deal with objects as pointers in Objective-C.</li>
                        <li>What this line is really doing is two things: [Fraction alloc] is calling the alloc method on the Fraction class.  This is similar to mallocing memory, because that is all that is done in this operation.</li>
                        <li>[object init] is the constructor call, which initializes any variables in the object.  This method is called on the instance returned from [Fraction alloc].  This operation is so common it's usually just done in one line as Object *var = [[Object alloc] init];
                    </ul>
                    <li>[frac setNumerator: 1] is quite simple.  It's calling the setNumerator method on frac, and passing it the parameter 1.</li>
                    <li>Like every c variant, there's a construct for freeing memory.  This is done via release, which is inherited from NSObject.  This method will be explainted in greater detail later.</li>
                </ul>
            </ul>
            <li><h1>The details...</h1><a name="thedetails"></a></li>
            <ul>
                <li><h2>Multiple Parameters</h2><a name="multiple"></a></li>
                <ul>
                    <li>Up until this point I haven't showed any way to specify multiple parameters.  It's not as intuitive at first, but it's syntax is a welcome addition from Smalltalk</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>Fraction.h<pre class="code">...
-(void) setNumerator: (int) n andDenominator: (int) d;
...</pre></li>
                    <li>Fraction.m<pre class="code">...
-(void) setNumerator: (int) n andDenominator: (int) d {
    numerator = n;
    denominator = d;
}
...</pre></li>
                    <li>main.m<pre class="code">#import &lt;stdio.h&gt;
#import "Fraction.h"

int main( int argc, const char *argv[] ) {
    // create a new instance
    Fraction *frac = [[Fraction alloc] init];
    Fraction *frac2 = [[Fraction alloc] init];

    // set the values
    [frac setNumerator: 1];
    [frac setDenominator: 3];

    // combined set
    [frac2 setNumerator: 1 andDenominator: 5];

    // print it
    printf( "The fraction is: " );
    [frac print];
    printf( "\n" );

    // print it
    printf( "Fraction 2 is: " );
    [frac2 print];
    printf( "\n" );

    // free memory
    [frac release];
    [frac2 release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">The fraction is: 1/3
Fraction 2 is: 1/5</pre></li>
                    <li>The method is actually called setNumerator:andDenominator:</li>
                    <li>Additional parameters are added the same was as the 2nd, such that you'd have method:label1:label2:label3: and you'd call it with [obj method: param1 label1: param2 label2: param3 label3: param4]</li>
                    <li>Labels are optional.  It's possible to have a method named method:::.  This is done by simply not specifing label names, but just a : to separate the parameters. This is however not advised.</li>
                </ul>
                <li><h2>Constructors</h2><a name="constructors"></a></li>
                <ul>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>Fraction.h<pre class="code">...
-(Fraction*) initWithNumerator: (int) n denominator: (int) d;
...</pre></li>
                    <li>Fraction.m<pre class="code">...
-(Fraction*) initWithNumerator: (int) n denominator: (int) d {
    self = [super init];

    if ( self ) {
        [self setNumerator: n andDenominator: d];
    }

    return self;
}
...</pre></li>
                    <li>main.m<pre class="code">#import &lt;stdio.h&gt;
#import "Fraction.h"

int main( int argc, const char *argv[] ) {
    // create a new instance
    Fraction *frac = [[Fraction alloc] init];
    Fraction *frac2 = [[Fraction alloc] init];
    Fraction *frac3 = [[Fraction alloc] initWithNumerator: 3 denominator: 10];

    // set the values
    [frac setNumerator: 1];
    [frac setDenominator: 3];

    // combined set
    [frac2 setNumerator: 1 andDenominator: 5];

    // print it
    printf( "The fraction is: " );
    [frac print];
    printf( "\n" );

    printf( "Fraction 2 is: " );
    [frac2 print];
    printf( "\n" );

    printf( "Fraction 3 is: " );
    [frac3 print];
    printf( "\n" );

    // free memory
    [frac release];
    [frac2 release];
    [frac3 release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">The fraction is: 1/3
Fraction 2 is: 1/5
Fraction 3 is: 3/10</pre></li>
                    <li>@interface declaration is identical to a regular function</li>
                    <li>@implementation shows a new keyword: super</li>
                    <ul>
                        <li>Similar to Java, Objective-C only has one parent class.</li>
                        <li>Accessing it's super constructor is done through [super init] and this is required for proper inheritance.</li>
                        <li>This returns an instance which you assign to another new keyword, self.  Self is similar to this in Java and C++.</li>
                    </ul>
                    <li>if ( self ) is the same as if ( self != nil ) to make sure that the super constructor successfully returned a new object.  nil is Objective-C's form of NULL from C/C++.  This is gotten from including NSObject.</li>
                    <li>After you've initialized the varialbes, you return yourself with return self;</li>
                    <li>The deafult constructor is -(id) init;</li>
                    <li>Constructors in Objective-C are technically just "init" methods, they aren't a special construct like they are in C++ and Java.</li>
                </ul>
                <li><h2>Access Privledges</h2><a name="access"></a></li>
                <ul>
                    <li>The default access is @protected</li>
                    <li>Java implements this with public/private/protected modifiers infront of methods and variables. Objective-C's approach is much more similar to C++'s for instance variables</li>
                    <li>Access.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;

@interface Access: NSObject {
@public
    int publicVar;
@private
    int privateVar;
    int privateVar2;
@protected
    int protectedVar;
}
@end</pre></li>
                    <li>Access.h<pre class="code">#import "Access.h"

@implementation Access
@end</pre></li>
                    <li>main.m<pre class="code">#import "Access.h"
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    Access *a = [[Access alloc] init];

    // works
    a-&gt;publicVar = 5;
    printf( "public var: %i\n", a-&gt;publicVar );

    // doesn't compile
    //a-&gt;privateVar = 10;
    //printf( "private var: %i\n", a-&gt;privateVar );

    [a release];
    return 0;
}</pre></li>
                    <li>output<pre class="output">public var: 5</pre></li>
                    <li>As you an see, instead of private: [list of vars] public: [list of vars] like in C++, it's just @private, @protected, etc.</li>
                </ul>
                <li><h2>Class level access</h2><a name="class"></a></li>
                <ul>
                    <li>Often it's nice to have class level variables and functions, for instance when keeping track of the # of times an object has been instanciated.</li>
                    <li>ClassA.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;

static int count;

@interface ClassA: NSObject
+(int) initCount;
+(void) initialize;
@end</pre></li>
                    <li>ClassA.m<pre class="code">#import "ClassA.h"

@implementation ClassA
-(id) init {
    self = [super init];
    count++;
    return self;
}

+(int) initCount {
    return count;
}

+(void) initialize {
    count = 0;
}
@end</pre></li>
                    <li>main.m<pre class="code">#import "ClassA.h"
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    ClassA *c1 = [[ClassA alloc] init];
    ClassA *c2 = [[ClassA alloc] init];

    // print count
    printf( "ClassA count: %i\n", [ClassA initCount] );
    
    ClassA *c3 = [[ClassA alloc] init];

    // print count again
    printf( "ClassA count: %i\n", [ClassA initCount] );

    [c1 release];
    [c2 release];
    [c3 release];
    
    return 0;
}</pre></li>
                    <li>output<pre class="output">ClassA count: 2
ClassA count: 3</pre></li>
                    <li>static int count = 0; This is how the class variable is declared.  This is not the ideal place for such a variable. A nicer solution would have been like Java's implementation of static class variables. However this works</li>
                    <li>+(int) initCount; This is the actual method that returns the count.  Notice the subtle difference.  Instead of using a - infront of the type, a + is used.  The + denotes a class level function.</li>
                    <li>Accessing the variable is no different than member variables, as seen by count++ in the constructor of ClassA.</li>
                    <li>The +(void) initialize method is called when Objective-C starts your program, and it's called for every class. This is a good place to initialize class level variables like our count.</li>
                </ul>
                <li><h2>Exceptions</h2><a name="exceptions"></a></li>
                <ul>
                    <li>NOTE: Exception handling is only supported in Mac OS X 10.3</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>CupWarningException.h<pre class="code">#import &lt;Foundation/NSException.h&gt;

@interface CupWarningException: NSException
@end</pre></li>
                    <li>CupWarningException.m<pre class="code">#import "CupWarningException.h"

@implementation CupWarningException
@end</pre></li>
                    <li>CupOverflowException.h<pre class="code">#import &lt;Foundation/NSException.h&gt;

@interface CupOverflowException: NSException
@end</pre></li>
                    <li>CupOverflowException.m<pre class="code">#import "CupOverflowException.h"

@implementation CupOverflowException
@end</pre></li>
                    <li>Cup.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;

@interface Cup: NSObject {
    int level;
}

-(int) level;
-(void) setLevel: (int) l;
-(void) fill;
-(void) empty;
-(void) print;
@end</pre></li>
                    <li>Cup.m<pre class="code">#import "Cup.h"
#import "CupOverflowException.h"
#import "CupWarningException.h"
#import &lt;Foundation/NSException.h&gt;
#import &lt;Foundation/NSString.h&gt;

@implementation Cup
-(id) init {
    self = [super init];

    if ( self ) {
        [self setLevel: 0];
    }

    return self;
}

-(int) level {
    return level;
}

-(void) setLevel: (int) l {
    level = l;

    if ( level &gt; 100 ) {
        // throw overflow
        NSException *e = [CupOverflowException
            exceptionWithName: @"CupOverflowException"
            reason: @"The level is above 100"
            userInfo: nil];
        @throw e;
    } else if ( level &gt;= 50 ) {
        // throw warning
        NSException *e = [CupWarningException
            exceptionWithName: @"CupWarningException"
            reason: @"The level is above or at 50"
            userInfo: nil];
        @throw e;
    } else if ( level &lt; 0 ) {
        // throw exception
        NSException *e = [NSException
            exceptionWithName: @"CupUnderflowException"
            reason: @"The level is below 0"
            userInfo: nil];
        @throw e;
    }
}

-(void) fill {
    [self setLevel: level + 10];
}

-(void) empty {
    [self setLevel: level - 10];
}

-(void) print {
    printf( "Cup level is: %i\n", level );
}
@end</pre></li>
                    <li>main.m<pre class="code">#import "Cup.h"
#import "CupOverflowException.h"
#import "CupWarningException.h"
#import &lt;Foundation/NSString.h&gt;
#import &lt;Foundation/NSException.h&gt;
#import &lt;Foundation/NSAutoreleasePool.h&gt;
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    Cup *cup = [[Cup alloc] init];
    int i;

    // this will work
    for ( i = 0; i &lt; 4; i++ ) {
        [cup fill];
        [cup print];
    }

    // this will throw exceptions
    for ( i = 0; i &lt; 7; i++ ) {
        @try {
            [cup fill];
        } @catch ( CupWarningException *e ) {
            printf( "%s: ", [[e name] cString] );
        } @catch ( CupOverflowException *e ) {
            printf( "%s: ", [[e name] cString] );
        } @finally {
            [cup print];
        }
    }

    // throw a generic exception
    @try {
        [cup setLevel: -1];
    } @catch ( NSException *e ) {
        printf( "%s: %s\n", [[e name] cString], [[e reason] cString] );
    }

    // free memory 
    [cup release];
    [pool release];
}</pre></li>
                    <li>output<pre class="output">Cup level is: 10
Cup level is: 20
Cup level is: 30
Cup level is: 40
CupWarningException: Cup level is: 50
CupWarningException: Cup level is: 60
CupWarningException: Cup level is: 70
CupWarningException: Cup level is: 80
CupWarningException: Cup level is: 90
CupWarningException: Cup level is: 100
CupOverflowException: Cup level is: 110
CupUnderflowException: The level is below 0</pre></li>
                    <li>NSAutoreleasePool is a memory management class. Don't worry about what this does right now.</li>
                    <li>Exceptions that are thrown don't have to extend NSException.  You can just as easily use an id as well: @catch ( id e ) { ... }</li>
                    <li>There is also a finally block, which behaves just like Java's.  The contents of a finally block are guaranteed to be called.</li>
                    <li>The string as show in Cup.m, @"CupOverflowException", is a constant NSString object.  The @ sign is used often in Objective-C to denote extentions to the language. A C string is just like C and C++, "String constant", and is of type char *.</li>
                </ul>
            </ul>
            <li><h1>Inheritance, Polymorphism, and other OOP features</h1><a name="inheritance"></a></li>
            <ul>
                <li><h2>The id type</h2><a name="idtype"></a></li>
                <ul>
                    <li>Objective-C has a type called id, that acts in some ways like a void*, though it's meant strictly for objects. Objective-C differs from Java and C++ in that when you call a method on an object, it doesn't need to know the type.  That method simply just has to exist.  This is refered to as message pasing in Objective-C.</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>Fraction.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;

@interface Fraction: NSObject {
    int numerator;
    int denominator;
}

-(Fraction*) initWithNumerator: (int) n denominator: (int) d;
-(void) print;
-(void) setNumerator: (int) d;
-(void) setDenominator: (int) d;
-(void) setNumerator: (int) n andDenominator: (int) d;
-(int) numerator;
-(int) denominator;
@end</pre></li>
                    <li>Fraction.m<pre class="code">#import "Fraction.h"
#import &lt;stdio.h&gt;

@implementation Fraction
-(Fraction*) initWithNumerator: (int) n denominator: (int) d {
    self = [super init];

    if ( self ) {
        [self setNumerator: n andDenominator: d];
    }

    return self;
}

-(void) print {
    printf( "%i / %i", numerator, denominator );
}

-(void) setNumerator: (int) n {
    numerator = n;
}

-(void) setDenominator: (int) d {
    denominator = d;
}

-(void) setNumerator: (int) n andDenominator: (int) d {
    numerator = n;
    denominator = d;
}

-(int) denominator {
    return denominator;
}

-(int) numerator {
    return numerator;
}
@end</pre></li>
                    <li>Complex.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;

@interface Complex: NSObject {
    double real;
    double imaginary;
}

-(Complex*) initWithReal: (double) r andImaginary: (double) i;
-(void) setReal: (double) r;
-(void) setImaginary: (double) i;
-(void) setReal: (double) r andImaginary: (double) i;
-(double) real;
-(double) imaginary;
-(void) print;

@end</pre></li>
                    <li>Complex.m<pre class="code">#import "Complex.h"
#import &lt;stdio.h&gt;

@implementation Complex
-(Complex*) initWithReal: (double) r andImaginary: (double) i {
    self = [super init];

    if ( self ) {
        [self setReal: r andImaginary: i];
    }

    return self;
}

-(void) setReal: (double) r {
    real = r;
}

-(void) setImaginary: (double) i {
    imaginary = i;
}

-(void) setReal: (double) r andImaginary: (double) i {
    real = r;
    imaginary = i;
}

-(double) real {
    return real;
}

-(double) imaginary {
    return imaginary;
}

-(void) print {
    printf( "%_f + %_fi", real, imaginary );
}

@end</pre></li>
                    <li>main.m<pre class="code">#import &lt;stdio.h&gt;
#import "Fraction.h"
#import "Complex.h"

int main( int argc, const char *argv[] ) {
    // create a new instance
    Fraction *frac = [[Fraction alloc] initWithNumerator: 1 denominator: 10];
    Complex *comp = [[Complex alloc] initWithReal: 10 andImaginary: 15];
    id number;

    // print fraction
    number = frac;
    printf( "The fraction is: " );
    [number print];
    printf( "\n" );

    // print complex
    number = comp;
    printf( "The complex number is: " );
    [number print];
    printf( "\n" );

    // free memory
    [frac release];
    [comp release];

    return 0;
}</pre></li>        
                    <li>output<pre class="output">The fraction is: 1 / 10
The complex number is: 10.000000 + 15.000000i</pre></li>
                    <li>There are obvious benefits to this type of dynamic binding.  You don't have to know the type of something to call a method on it.  If the object responds to a message, it will invoke that method. Lots of nasty casting isn't involved in this either, such as in Java to call .intValue() on an integer object would involve casting first, then calling the method.</li>
                </ul>
                <li><h2>Inheritance</h2><a name="subinheritance"></a></li>
                <ul>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>Rectangle.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;

@interface Rectangle: NSObject {
    int width;
    int height;
}

-(Rectangle*) initWithWidth: (int) w height: (int) h;
-(void) setWidth: (int) w;
-(void) setHeight: (int) h;
-(void) setWidth: (int) w height: (int) h;
-(int) width;
-(int) height;
-(void) print;
@end</pre></li>
                    <li>Rectangle.m<pre class="code">#import "Rectangle.h"
#import &lt;stdio.h&gt;

@implementation Rectangle
-(Rectangle*) initWithWidth: (int) w height: (int) h {
    self = [super init];

    if ( self ) {
        [self setWidth: w height: h];
    }

    return self;
}

-(void) setWidth: (int) w {
    width = w;
}

-(void) setHeight: (int) h {
    height = h;
}

-(void) setWidth: (int) w height: (int) h {
    width = w;
    height = h;
}

-(int) width {
    return width;
}

-(int) height {
    return  height;
}

-(void) print {
    printf( "width = %i, height = %i", width, height );
}
@end</pre></li>
                    <li>Square.h<pre class="code">#import "Rectangle.h"

@interface Square: Rectangle
-(Square*) initWithSize: (int) s;
-(void) setSize: (int) s;
-(int) size;
@end</pre></li>
                    <li>Square.m<pre class="code">#import "Square.h"

@implementation Square
-(Square*) initWithSize: (int) s {
    self = [super init];

    if ( self ) {
        [self setSize: s];
    }

    return self;
}

-(void) setSize: (int) s {
    width = s;
    height = s;
}

-(int) size {
    return width;
}

-(void) setWidth: (int) w {
    [self setSize: w];
}

-(void) setHeight: (int) h {
    [self setSize: h];
}
@end</pre></li>
                    <li>main.m<pre class="code">#import "Square.h"
#import "Rectangle.h"
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    Rectangle *rec = [[Rectangle alloc] initWithWidth: 10 height: 20];
    Square *sq = [[Square alloc] initWithSize: 15];

    // print em
    printf( "Rectangle: " );
    [rec print];
    printf( "\n" );

    printf( "Square: " );
    [sq print];
    printf( "\n" );

    // update square
    [sq setWidth: 20];
    printf( "Square after change: " );
    [sq print];
    printf( "\n" );

    // free memory
    [rec release];
    [sq release];
    
    return 0;
}</pre></li>
                    <li>output<pre class="output">Rectangle: width = 10, height = 20
Square: width = 15, height = 15
Square after change: width = 20, height = 20</pre></li>
                    <li>Inheritance in Objective-C is similar to Java. When you extend your super class (of which you can only have one parent) you can override the methods of your super class by simply putting the new implementations in the child classes implementation.  No fooling with virtual tables like C++.</li>
                    <li>One thing left out here that is worth nothing is what would happen if you attempted to call the constructor for rectangle like: Square *sq = [[Square alloc] initWithWidth: 10 height: 15].  The answer is it will throw a compile error.  Since the return type of the rectangle constructor is Rectangle*, not Square* this would not work.  In such a case if you want this to occur, that's what the id variable is good for.  Just change the Rectangle* return type to id if you wish to use your parent's constructors in a subclass.</li>
                </ul>
                <li><h2>Dynamic types</h2><a name="dynamictypes"></a></li>
                <ul>
                    <li>There are several methods for working with dynamic types in Objective-C</li>
                    <ul>
                        <table border="2" cellspacing="0">
                            <tr>
                                <td width="300">-(BOOL) isKindOfClass: classObj</td>
                                <td>is object a descendent or member of classObj</td>
                            </tr>
                            <tr>
                                <td>-(BOOL) isMemberOfClass: classObj</td>
                                <td>is object a member of classObj</td>
                            </tr>
                            <tr>
                                <td>-(BOOL) respondsToSelector: selector</td>
                                <td>does the object have a method named specifiec by the selector</td>
                            </tr>
                            <tr>
                                <td>+(BOOL) instancesRespondToSelector: selector</td>
                                <td>does an object created by this class have the ability to respond to the specified selector</td>
                            </tr>
                            <tr>
                                <td>-(id) performSelector: selector</td>
                                <td>invoke the specified selector on the object</td>
                            </tr>
                        </table>
                    </ul>
                    <li>Every object inherited from NSObject has a class method that returns a class object.  This is very similar to Java's getClass() method.  This class object is used in the methods above.</li>
                    <li>Selectors are used to represent a message in Objective-C.  The syntax for creating a selector is shown in the next example</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>main.m<pre class="code">#import "Square.h"
#import "Rectangle.h"
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    Rectangle *rec = [[Rectangle alloc] initWithWidth: 10 height: 20];
    Square *sq = [[Square alloc] initWithSize: 15];

    // isMemberOfClass

    // true 
    if ( [sq isMemberOfClass: [Square class]] == YES ) {
        printf( "square is a member of square class\n" );
    }

    // false
    if ( [sq isMemberOfClass: [Rectangle class]] == YES ) {
        printf( "square is a member of rectangle class\n" );
    }

    // false
    if ( [sq isMemberOfClass: [NSObject class]] == YES ) {
        printf( "square is a member of object class\n" );
    }

    // isKindOfClass
    
    // true 
    if ( [sq isKindOfClass: [Square class]] == YES ) {
        printf( "square is a kind of square class\n" );
    }

    // true
    if ( [sq isKindOfClass: [Rectangle class]] == YES ) {
        printf( "square is a kind of rectangle class\n" );
    }

    // true
    if ( [sq isKindOfClass: [NSObject class]] == YES ) {
        printf( "square is a kind of object class\n" );
    }

    // respondsToSelector

    // true
    if ( [sq respondsToSelector: @selector( setSize: )] == YES ) {
        printf( "square responds to setSize: method\n" );
    }

    // false
    if ( [sq respondsToSelector: @selector( nonExistant )] == YES ) {
        printf( "square responds to nonExistant method\n" );
    }

    // true
    if ( [Square respondsToSelector: @selector( alloc )] == YES ) {
        printf( "square class responds to alloc method\n" );
    }

    // instancesRespondToSelector

    // false
    if ( [Rectangle instancesRespondToSelector: @selector( setSize: )] == YES ) {
        printf( "rectangle instance responds to setSize: method\n" );
    }

    // true
    if ( [Square instancesRespondToSelector: @selector( setSize: )] == YES ) {
        printf( "square instance responds to setSize: method\n" );
    }

    // free memory
    [rec release];
    [sq release];
    
    return 0;
}</pre></li>
                    <li>output<pre class="output">square is a member of square class
square is a kind of square class
square is a kind of rectangle class
square is a kind of object class
square responds to setSize: method
square class responds to alloc method
square instance responds to setSize: method</pre></li>
                </ul>
                <li><h2>Categories</h2></li>
                <ul>
                    <li>When you want to add methods to a class, you typically extend it.  However this solution isn't always perfect, especially if you want to rewrite the functionality of a class that you don't have the source code to.  Categories allow you to add functionality to already existing classes without extending them.  Ruby also has similar functionality to this.</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>FractionMath.h<pre class="code">#import "Fraction.h"

@interface Fraction (Math)
-(Fraction*) add: (Fraction*) f;
-(Fraction*) mul: (Fraction*) f;
-(Fraction*) div: (Fraction*) f;
-(Fraction*) sub: (Fraction*) f;
@end</pre></li>
                    <li>FractionMath.m<pre class="code">#import "FractionMath.h"

@implementation Fraction (Math)
-(Fraction*) add: (Fraction*) f {
    return [[Fraction alloc] initWithNumerator: numerator * [f denominator] +
                                                denominator * [f numerator]
                             denominator: denominator * [f denominator]];
}

-(Fraction*) mul: (Fraction*) f {
    return [[Fraction alloc] initWithNumerator: numerator * [f numerator]
                             denominator: denominator * [f denominator]];

}

-(Fraction*) div: (Fraction*) f {
    return [[Fraction alloc] initWithNumerator: numerator * [f denominator]
                             denominator: denominator * [f numerator]];
}

-(Fraction*) sub: (Fraction*) f {
    return [[Fraction alloc] initWithNumerator: numerator * [f denominator] -
                                                denominator * [f numerator]
                             denominator: denominator * [f denominator]];
}
@end</pre></li>
                    <li>main.m<pre class="code">#import &lt;stdio.h&gt;
#import "Fraction.h"
#import "FractionMath.h"

int main( int argc, const char *argv[] ) {
    // create a new instance
    Fraction *frac1 = [[Fraction alloc] initWithNumerator: 1 denominator: 3];
    Fraction *frac2 = [[Fraction alloc] initWithNumerator: 2 denominator: 5];
    Fraction *frac3 = [frac1 mul: frac2];

    // print it
    [frac1 print];
    printf( " * " );
    [frac2 print];
    printf( " = " );
    [frac3 print];
    printf( "\n" );

    // free memory
    [frac1 release];
    [frac2 release];
    [frac3 release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">1/3 * 2/5 = 2/15</pre></li>
                    <li>The magic here is the two @implementation and @interface lines:  @interface Fraction (Math) and @implementation Fraction (Math).</li>
                    <li>There can only be one category with the same name. Additional cateogies may be added on with different but unqiue names.</li>
                    <li>Categories can't add instance variables.</li>
                    <li>Categories are useful for creating private methods. Since Objective-C has no notion of private/protected/public methods like java does, one has to create categories that hide such functionality.  The way this is done is by moving the private methods from your class's header (.h) file to the implementation file (.m). The following is a very brief example of what I mean.</li>
                    <li>MyClass.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;

@interface MyClass: NSObject
-(void) publicMethod;
@end</pre></li>
                    <li>MyClass.m<pre class="code">#import "MyClass.h"
#import &lt;stdio.h&gt;

@implementation MyClass
-(void) publicMethod {
    printf( "public method\n" );
}
@end

// private methods
@interface MyClass (Private)
-(void) privateMethod;
@end

@implementation MyClass (Private)
-(void) privateMethod {
    printf( "private method\n" );
}
@end</pre></li>
                    <li>main.m<pre class="code">#import "MyClass.h"

int main( int argc, const char *argv[] ) {
    MyClass *obj = [[MyClass alloc] init];

    // this compiles
    [obj publicMethod];

    // this throws errors when compiling
    //[obj privateMethod];

    // free memory
    [obj release];
    
    return 0;
}</pre></li>
                    <li>output<pre class="output">public method</pre></li>
                </ul>
                <li><h2>Posing</h2><a name="posing"></a></li>
                <ul>
                    <li>Posing is similar to categories, but with a twist. It allows you to extend a class, and make your subclass pose (in place of) the super class globally.  For instance: Say you have NSArrayChild that extends NSArray.  If you made NSArrayChild pose for NSArray all your code would begin using the NSArrayChild instead of NSArray automatically.</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>FractionB.h<pre class="code">#import "Fraction.h"

@interface FractionB: Fraction
-(void) print;
@end
</pre></li>
                    <li>FractionB.m<pre class="code">#import "FractionB.h"
#import &lt;stdio.h&gt;

@implementation FractionB
-(void) print {
    printf( "(%i/%i)", numerator, denominator );
}
@end</pre></li>
                    <li>main.m<pre class="code">#import &lt;stdio.h&gt;
#import "Fraction.h"
#import "FractionB.h"

int main( int argc, const char *argv[] ) {
    Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10];

    // print it
    printf( "The fraction is: " );
    [frac print];
    printf( "\n" );

    // make FractionB pose as Fraction
    [FractionB poseAsClass: [Fraction class]];

    Fraction *frac2 = [[Fraction alloc] initWithNumerator: 3 denominator: 10];

    // print it
    printf( "The fraction is: " );
    [frac2 print];
    printf( "\n" );

    // free memory
    [frac release];
    [frac2 release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">The fraction is: 3/10
The fraction is: (3/10)</pre></li>
                    <li>The output from this program would print the first fraction s 3/10.  The second would output (3/10), which is implemented by FractionB.</li>
                    <li>The method poseAsClass is part of NSObject.  This allows a subclass to pose as a superclass.</li>
                </ul>
                <li><h2>Protocols</h2><a name="protocols"></a></li>
                <ul>
                    <li>A Protocol in Objective-C is identical in functionality to an interface in Java, or a purely virtual class in C++.</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>Printing.h<pre class="code">@protocol Printing
-(void) print;
@end</pre></li>
                    <li>Fraction.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;
#import "Printing.h"

@interface Fraction: NSObject &lt;Printing, NSCopying&gt; {
    int numerator;
    int denominator;
}

-(Fraction*) initWithNumerator: (int) n denominator: (int) d;
-(void) setNumerator: (int) d;
-(void) setDenominator: (int) d;
-(void) setNumerator: (int) n andDenominator: (int) d;
-(int) numerator;
-(int) denominator;
@end</pre></li>
                    <li>Fraction.m<pre class="code">#import "Fraction.h"
#import &lt;stdio.h&gt;

@implementation Fraction
-(Fraction*) initWithNumerator: (int) n denominator: (int) d {
    self = [super init];

    if ( self ) {
        [self setNumerator: n andDenominator: d];
    }

    return self;
}

-(void) print {
    printf( "%i/%i", numerator, denominator );
}

-(void) setNumerator: (int) n {
    numerator = n;
}

-(void) setDenominator: (int) d {
    denominator = d;
}

-(void) setNumerator: (int) n andDenominator: (int) d {
    numerator = n;
    denominator = d;
}

-(int) denominator {
    return denominator;
}

-(int) numerator {
    return numerator;
}

-(Fraction*) copyWithZone: (NSZone*) zone {
    return [[Fraction allocWithZone: zone] initWithNumerator: numerator
                                           denominator: denominator];
}
@end</pre></li>
                    <li>Complex.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;
#import "Printing.h"

@interface Complex: NSObject &lt;Printing&gt; {
    double real;
    double imaginary;
}

-(Complex*) initWithReal: (double) r andImaginary: (double) i;
-(void) setReal: (double) r;
-(void) setImaginary: (double) i;
-(void) setReal: (double) r andImaginary: (double) i;
-(double) real;
-(double) imaginary;
@end</pre></li>
                    <li>Complex.m<pre class="code">#import "Complex.h"
#import &lt;stdio.h&gt;

@implementation Complex
-(Complex*) initWithReal: (double) r andImaginary: (double) i {
    self = [super init];

    if ( self ) {
        [self setReal: r andImaginary: i];
    }

    return self;
}

-(void) setReal: (double) r {
    real = r;
}

-(void) setImaginary: (double) i {
    imaginary = i;
}

-(void) setReal: (double) r andImaginary: (double) i {
    real = r;
    imaginary = i;
}

-(double) real {
    return real;
}

-(double) imaginary {
    return imaginary;
}

-(void) print {
    printf( "%_f + %_fi", real, imaginary );
}
@end</pre></li>
                    <li>main.m<pre class="code">#import &lt;stdio.h&gt;
#import "Fraction.h"
#import "Complex.h"

int main( int argc, const char *argv[] ) {
    // create a new instance
    Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10];
    Complex *comp = [[Complex alloc] initWithReal: 5 andImaginary: 15];
    id &lt;Printing&gt; printable;
    id &lt;NSCopying, Printing&gt; copyPrintable;

    // print it
    printable = frac;
    printf( "The fraction is: " );
    [printable print];
    printf( "\n" );

    // print complex
    printable = comp;
    printf( "The complex number is: " );
    [printable print];
    printf( "\n" );

    // this compiles because Fraction comforms to both Printing and NSCopyable
    copyPrintable = frac;

    // this doesn't compile because Complex only conforms to Printing
    //copyPrintable = comp;

    // test conformance

    // true
    if ( [frac conformsToProtocol: @protocol( NSCopying )] == YES ) {
        printf( "Fraction conforms to NSCopying\n" );
    }

    // false
    if ( [comp conformsToProtocol: @protocol( NSCopying )] == YES ) {
        printf( "Complex conforms to NSCopying\n" );
    }

    // free memory
    [frac release];
    [comp release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">The fraction is: 3/10
The complex number is: 5.000000 + 15.000000i
Fraction conforms to NSCopying</pre></li>
                    <li>The protocol specification is quite simple.  it is basically @protocol ProtocolName (methods you must implement) @end.</li>
                    <li>To conform to a protocol, you put the protocols you're conforming to in &lt;&gt;'s, and comma separate them. Example: @interface SomeClass &lt;Protocol1, Protocol2, Protocol3&gt;</li>
                    <li>The methods that the protocol requires to be implemented are not required to be in the list of methods for the header file.  As you can see, Complex.h doesn't have a definition for -(void) print, but it still implements it since it conforms to the protocol.</li>
                    <li>One unique aspect of Objective-C's interface system is how you specify types.  Rather than specifying it like Java or C++ as: Printing *someVar = ( Printing * ) frac; for example, you use the id type with a restricted protocol: id &lt;Printing&gt; var = frac; This allows you to dynamically specify a type that requires multiple protocols, all with one variable.  Such as: id &lt;Printing, NSCopying&gt; var = frac;</li>
                    <li>Much like using @selector for testing an object's inheritance, you can use @protocol to test for conformance of interfaces. [object conformsToProtocol: @protocol( SomeProtocol )] returns a BOOL if the object conforms to that protocol.  This works the same for classes as well: [SomeClass conformsToProtocol: @protocol( SomeProtocol )].</li>
                </ul>
            </ul>
            <li><h1>Memory Management</h1><a name="memorymanagement"></a></li>
            <ul>
                <li>Up until now I've kind of dodged memory management in Objective-C.  Sure you can call dealloc on an object, but what happens if the object contains pointers to other objects?  One has to be concerned about freeing the memory of those objects as well.  Also how does the Foundation framework manage memory when you create classes from it?  This will all be explained.</li>
                <li>Note: everything up until this point has been properly memory managed, incase you're wondering.</li>
                <li><h2>Retain and Release</h2><a name="retain"></a></li>
                <ul>
                    <li>Retain and release are two methods inherited from any object that has NSObject as a parent.  Each object has an internal counter that can be used to keep track of the number references an object has.  So if you have 3 referneces, you don't want to dealloc yourself.  However once you reach 0, you should dealloc yourself.  [object retain] increments the counter by 1 (which starts at 1) and [object release] decrements it by 1.  If the [object release] invocation causes the count to reach 0, dealloc is then called.</li>
                    <li>Fraction.m<pre class="code">...
-(void) dealloc {
    printf( "Deallocing fraction\n" );
    [super dealloc];
}
...</pre></li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>main.m<pre class="code">#import "Fraction.h"
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    Fraction *frac1 = [[Fraction alloc] init];
    Fraction *frac2 = [[Fraction alloc] init];

    // print current counts
    printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] );
    printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] );

    // increment them
    [frac1 retain]; // 2
    [frac1 retain]; // 3
    [frac2 retain]; // 2

    // print current counts
    printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] );
    printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] );

    // decrement
    [frac1 release]; // 2
    [frac2 release]; // 1

    // print current counts
    printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] );
    printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] );
    
    // release them until they dealloc themselves
    [frac1 release]; // 1
    [frac1 release]; // 0
    [frac2 release]; // 0
}</pre></li>
                    <li>output<pre class="output">Fraction 1 retain count: 1
Fraction 2 retain count: 1
Fraction 1 retain count: 3
Fraction 2 retain count: 2
Fraction 1 retain count: 2
Fraction 2 retain count: 1
Deallocing fraction
Deallocing fraction</pre></li>
                    <li>The retain calls increment the counter.  The release calls decrement it.  One can get the count as an int by calling [obj retainCount].  Once the retainCount reaches 0, both objects dealloc themselves and you can see this when both print out "Deallocing fraction."</li>
                </ul>
                <li><h2>Dealloc</h2><a name="dealloc"></a></li>
                <ul>
                    <li>When your object contains other objects, you must free them whenever you yourself dealloc.  One of the nice advantages to Objective-C is you can pass messages to nil, so there isn't a lot of error checking to release an object.</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>AddressCard.h<pre class="code">#import &lt;Foundation/NSObject.h&gt;
#import &lt;Foundation/NSString.h&gt;

@interface AddressCard: NSObject {
    NSString *first;
    NSString *last;
    NSString *email;
}

-(AddressCard*) initWithFirst: (NSString*) f
                last: (NSString*) l
                email: (NSString*) e;
-(NSString*) first;
-(NSString*) last;
-(NSString*) email;
-(void) setFirst: (NSString*) f;
-(void) setLast: (NSString*) l;
-(void) setEmail: (NSString*) e;
-(void) setFirst: (NSString*) f
        last: (NSString*) l
        email: (NSString*) e;
-(void) setFirst: (NSString*) f last: (NSString*) l;
-(void) print;
@end</pre></li>
                    <li>AddressCard.m<pre class="code">#import "AddressCard.h"
#import &lt;stdio.h&gt;

@implementation AddressCard
-(AddressCard*) initWithFirst: (NSString*) f
                last: (NSString*) l
                email: (NSString*) e {
    self = [super init];

    if ( self ) {
        [self setFirst: f last: l email: e];
    }

    return self;
}

-(NSString*) first {
    return first;
}

-(NSString*) last {
    return last;
}

-(NSString*) email {
    return email;
}

-(void) setFirst: (NSString*) f {
    [f retain];
    [first release];
    first = f;
}

-(void) setLast: (NSString*) l {
    [l retain];
    [last release];
    last = l;
}

-(void) setEmail: (NSString*) e {
    [e retain];
    [email release];
    email = e;
}

-(void) setFirst: (NSString*) f
        last: (NSString*) l
        email: (NSString*) e {
    [self setFirst: f];
    [self setLast: l];
    [self setEmail: e];
}

-(void) setFirst: (NSString*) f last: (NSString*) l {
    [self setFirst: f];
    [self setLast: l];
}

-(void) print {
    printf( "%s %s &lt;%s&gt;", [first cString],
                                [last cString],
                                [email cString] );
}

-(void) dealloc {
    [first release];
    [last release];
    [email release];

    [super dealloc];
}
@end</pre></li>
                    <li>main.m<pre class="code">#import "AddressCard.h"
#import &lt;Foundation/NSString.h&gt;
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    NSString *first =[[NSString alloc] initWithCString: "Tom"];
    NSString *last = [[NSString alloc] initWithCString: "Jones"];
    NSString *email = [[NSString alloc] initWithCString: "tom@jones.com"];
    AddressCard *tom = [[AddressCard alloc] initWithFirst: first
                                            last: last
                                            email: email];

    // we're done with the strings, so we must dealloc them
    [first release];
    [last release];
    [email release];

    // print to show the retain count
    printf( "Retain count: %i\n", [[tom first] retainCount] );
    [tom print];
    printf( "\n" );
    
    // free memory
    [tom release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">Retain count: 1
Tom Jones &lt;tom@jones.com&gt;</pre></li>
                    <li>This example shows not only how to make a dealloc method, as shown in AddressCard.m, but one way to do member variables.</li>
                    <li>The order of the 3 operations in each set method is very important. Lets say you'return passing a parameter of yourself to one of your methods (a bit of an odd example, but this can happen).  If you release first, THEN retain you will destruct yourself!  That's why you should always 1) retain 2) release 3) set the value.</li>
                    <li>Normally one wouldn't initialize variables with C strings because they don't support unicode.  The next example, with NSAutoreleasePool shows the proper way to do strings and initializing.</li>
                    <li>This is just one way of handling member variable memory management. One way to handle this is to create copies inside your set methods.</li>
                </ul>
                <li><h2>Autorelease Pool</h2><a name="autorelease"></a>
                <ul>
                    <li>When you want to start doing more programming using NSString and other Foundation framework classes you need a more flexible system.  This system is using Autorelease pools.</li>
                    <li>When developing Mac Cocoa applications, the auto release pool is setup automatically for you.</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>main.m<pre class="code">#import &lt;Foundation/NSString.h&gt;
#import &lt;Foundation/NSAutoreleasePool.h&gt;
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *str1 = @"constant string";
    NSString *str2 = [NSString stringWithString: @"string managed by the pool"];
    NSString *str3 = [[NSString alloc] initWithString: @"self managed string"];

    // print the strings
    printf( "%s retain count: %x\n", [str1 cString], [str1 retainCount] );
    printf( "%s retain count: %x\n", [str2 cString], [str2 retainCount] );
    printf( "%s retain count: %x\n", [str3 cString], [str3 retainCount] );

    // free memory
    [str3 release];

    // free pool
    [pool release];
    return 0;
}</pre></li>
                    <li>output<pre class="output">constant string retain count: ffffffff
string managed by the pool retain count: 1
self managed string retain count: 1</pre></li>
                    <li>If you run this you'll notice a few things. One is that the retainCount of str1 is ffffffff.</li>
                    <li>The other is, I only release str3, yet this program is memory management perfect.  The reason is the first constant string is added to the autorelease pool automatically.  The other string is made using stringWithString.  This method creates a string that is owned by NSString class, which also puts it in the auto release pool.</li>
                    <li>It's important to remember, for proper memory management, that convience methods like [NSString stringWithString: @"String"] use autorelease pools, but alloc methods like [[NSString alloc] initWithString: @"String"] do not use autorelease pools for managing memory.</li>
                    <li>There are two ways to manage memory in Objective-C: 1) retain and release or 2) retain and release/autorelease.</li>
                    <li>For each retain, there must be one release OR one autorelease.</li>
                    <li>The following example shows what I mean by this</li>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>Fraction.h<pre class="code">...
+(Fraction*) fractionWithNumerator: (int) n denominator: (int) d;
...
</pre></li>
                    <li>Fraction.m<pre class="code">...
+(Fraction*) fractionWithNumerator: (int) n denominator: (int) d {
    Fraction *ret = [[Fraction alloc] initWithNumerator: n denominator: d];
    [ret autorelease];

    return ret;
}
...</pre></li>
                    <li>main.m<pre class="code">#import &lt;Foundation/NSAutoreleasePool.h&gt;
#import "Fraction.h"
#import &lt;stdio.h&gt;

int main( int argc, const char *argv[] ) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    Fraction *frac1 = [Fraction fractionWithNumerator: 2 denominator: 5];
    Fraction *frac2 = [Fraction fractionWithNumerator: 1 denominator: 3];

    // print frac 1
    printf( "Fraction 1: " );
    [frac1 print];
    printf( "\n" );

    // print frac 2
    printf( "Fraction 2: " );
    [frac2 print];
    printf( "\n" );

    // this causes a segmentation fault
    //[frac1 release];

    // release the pool and all objects in it
    [pool release];
    return 0;
}</pre></li>
                    <li>output<pre class="output">Fraction 1: 2/5
Fraction 2: 1/3</pre></li>
                    <li>In this example, the method is a class level method. After the object is created, autorelease is called on it. Inside the body of the main method, I never call release on the object.</li>
                    <li>The reason this works is because: for every retain, one release or autorelease must be called. The object's retain count starts out as 1, and I called autorelease on it once. This means 1 - 1 = 0. Once the autorelease pool is released, it counts the autorelease calls on all objects and decrements them with [obj release] with the same number of times autorelease was called per object.</li>
                    <li>As the comment says, uncommenting that line causes a segment fault.  Since autorelease was already called on the object, calling release on it, and then releasing the autorelease pool would attempt to call dealloc on an object that is nil, which is not valid.  The end math is 1 (creation) - 1 (release) - 1 (autorelease) = -1.</li>
                    <li>Auto release pools can be dynamically created for large amounts of temporary objects.  All one must do is create a pool, perform any large chunk of code that creates lots of temporary objects, then release the pool.  As you may wonder, it this means it is possible to have more than one auto release pool at a time.</li>
                </ul>
            </ul>
            <li><h1>Foundation framework classes</h1><a name="foundation"></a></li>
            <ul>
                <li>The Foundation framework is similar to C++'s Standard Template Library.  Although since Objective-C has real dynamic types, the horrible cludge that is C++'s templating is not necessary.  This framework contains collections, networking, threading, and much more.</li>
                <li><h2>NSArray</h2><a name="nsarray"></a></li>
                <ul>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>main.m<pre class="code">#import &lt;Foundation/NSArray.h&gt;
#import &lt;Foundation/NSString.h&gt;
#import &lt;Foundation/NSAutoreleasePool.h&gt;
#import &lt;Foundation/NSEnumerator.h&gt;
#import &lt;stdio.h&gt;

void print( NSArray *array ) {
    NSEnumerator *enumerator = [array objectEnumerator];
    id obj;

    while ( obj = [enumerator nextObject] ) {
        printf( "%s\n", [[obj description] cString] );
    }
}

int main( int argc, const char *argv[] ) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSArray *arr = [[NSArray alloc] initWithObjects:
                    @"Me", @"Myself", @"I", nil];
    NSMutableArray *mutable = [[NSMutableArray alloc] init];

    // enumerate over items
    printf( "----static array\n" );
    print( arr );

    // add stuff
    [mutable addObject: @"One"];
    [mutable addObject: @"Two"];
    [mutable addObjectsFromArray: arr];
    [mutable addObject: @"Three"];

    // print em
    printf( "----mutable array\n" );
    print( mutable );

    // sort then print
    printf( "----sorted mutable array\n" );
    [mutable sortUsingSelector: @selector( caseInsensitiveCompare: )];
    print( mutable );
    
    // free memory
    [arr release];
    [mutable release];
    [pool release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">----static array
Me
Myself
I
----mutable array
One
Two
Me
Myself
I
Three
----sorted mutable array
I
Me
Myself
One
Three
Two</pre></li>
                    <li>There are two kinds of arrays (and of usually most data oriented Foundation classes) NSArray and NSMutableArray. As the name suggests, Mutable is changable, NSArray then is not.  This means you can make an NSArray but once you have you can't change the length.</li>
                    <li>You initialize an array via the constructor using Obj, Obj, Obj, ..., nil.  The nil is an ending delimiter.</li>
                    <li>The sorting shows how to sort an object using a selector.  The selector tells the array to sort using NSString's case insensitive compare.  If your object has several sort methods, you can choose anyone you want using this selector.</li>
                    <li>In the print method, I used the method description. This is similar to Java's toString.  It returns an NSString representation of an object.</li>
                    <li>NSEnumerator is similar to Java's enumerator system.  The reason why while ( obj = [array objectEnumerator] ) works is because objectEnumerator returns nil on the last object. Since in C nil is usually 0, this is the same as false.  ( ( obj = [array objectEnumerator] ) != nil ) might be preferable</li>
                </ul>
                <li><h2>NSDictionary</h2><a name="nsdictionary"></a></li>
                <ul>
                    <li><span class="notice">Based on an example in "Programming in Objective-C,"  Copyright &copy; 2004 by Sams Publishing.  Used with permission</span></li>
                    <li>main.m<pre class="code">#import &lt;Foundation/NSString.h&gt;
#import &lt;Foundation/NSAutoreleasePool.h&gt;
#import &lt;Foundation/NSDictionary.h&gt;
#import &lt;Foundation/NSEnumerator.h&gt;
#import &lt;Foundation/Foundation.h&lt;
#import &lt;stdio.h&gt;

void print( NSDictionary *map ) {
    NSEnumerator *enumerator = [map keyEnumerator];
    id key;

    while ( key = [enumerator nextObject] ) {
        printf( "%s =&gt; %s\n",
                [[key description] cString],
                [[[map objectForKey: key] description] cString] );
    }
}

int main( int argc, const char *argv[] ) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
        @"one", [NSNumber numberWithInt: 1],
        @"two", [NSNumber numberWithInt: 2],
        @"three", [NSNumber numberWithInt: 3],
        nil];
    NSMutableDictionary *mutable = [[NSMutableDictionary alloc] init];

    // print dictionary
    printf( "----static dictionary\n" );
    print( dictionary );

    // add objects
    [mutable setObject: @"Tom" forKey: @"tom@jones.com"];
    [mutable setObject: @"Bob" forKey: @"bob@dole.com" ];

    // print mutable dictionary
    printf( "----mutable dictionary\n" );
    print( mutable );

    // free memory 
    [dictionary release];
    [mutable release];
    [pool release];

    return 0;
}</pre></li>
                    <li>output<pre class="output">----static dictionary
1 =&gt; one
2 =&gt; two
3 =&gt; three
----mutable dictionary
bob@dole.com =&gt; Bob
tom@jones.com =&gt; Tom</pre></li>
                </ul>
            </ul>
            <li><h1>Pros and Cons</h1><a name="prosandcons"></a></li>
            <ul>
                <li><h2>Pros</h2></li>
                <ul>
                    <li>Cateogies</li>
                    <li>Posing</li>
                    <li>Dynamic typing</li>
                    <li>Pointer counting</li>
                    <li>Flexible message passing</li>
                    <li>Not an overly complex extention to C</li>
                    <li>Can interface with C++ via Objective-C++</li>
                </ul>
                <li><h2>Cons</h2></li>
                <ul>
                    <li>No namespaces</li>
                    <li>No operator overloading (this is often considered a Pro though, but operator overloading used <b>properly</b> can reduce code clutter)</li>
                    <li>Still some cruft in language, although no more than C++</li>
                </ul>
            </ul>
            <li><h1>More Information</h1><a name="moreinfo"></a></li>
            <ul>
                <li><a href="http://www.toodarkpark.org/computers/objc/">Object-Oriented Programming and the Objective-C Language</a></li>
                <li><a href="http://www.gnustep.it/nicola/Tutorials/index.html">GNUstep mini tutorials</a></li>
                <li><a href="http://www.amazon.com/exec/obidos/tg/detail/-/0672325861/qid=1080660707/sr=8-1/ref=pd_ka_1/104-8175678-0659956?v=glance&s=books&n=507846">Programming in Objective C</a></li>
                <li><a href="http://www.amazon.com/exec/obidos/tg/detail/-/0596003013/qid=1080660707/sr=8-1/ref=sr_8_xs_ap_i1_xgl14/104-8175678-0659956?v=glance&s=books&n=507846">Learning Cocoa with Objective-C</a></li>
            </ul>
        </ul>
        <hr />
        Last modified: April 13, 2004.
    </body>
</html>
